<template>
    <div class="phone-login">
        <el-form ref="formRef" :model="form" class="form">
            <el-form-item :required="true" prop="phone">
                <el-input placeholder="请输入手机号" v-model="form.phone" prefix-icon="User" />
            </el-form-item>
            <el-form-item :required="true" prop="code">
                <PhoneMessage v-model="form.code" :phone="form.phone" prefix-icon="Message" />
            </el-form-item>
        </el-form>

        <div class="buttons text-center">
            <el-button type="primary" @click="login" class="w-100 button">登录</el-button>
        </div>

        <div class="color-red error-msg">
            {{ errorInfo.msg }}
        </div>
    </div>
</template>
<script setup>
import * as _ from "lodash";
import PhoneMessage from "../../../components/form/phone-message-input.vue";
import * as sysApis from "@/apis/sys.js";
import { ElMessage } from "element-plus";
import { setToken } from "../../../utils/token";
import { useSysStore } from "../../../store";

const emits = defineEmits(["next"]);
const form = ref({});
const formRef = ref();
const sysStore = useSysStore();
const errorInfo = ref({});

function login() {
    formRef.value.validate((res) => {
        if (!res) {
            return;
        }

        app.https
            .get("/auth/login-by-phone", form.value)
            .then((resp) => {
                setToken(resp.accessToken);

                sysApis.getInitInfo().then((resp) => {
                    ElMessage.success("登录成功");
                    setTimeout(() => {
                        sysStore.init(resp);
                    }, 30);
                    emits("next");
                });
            })
            .catch((err) => {
                console.log(err);
                errorInfo.value = err;
            });
    });
}
</script>

<style lang="scss" scoped>
.form {
    .img {
        height: 34px;
    }

    :deep() {
        .el-input {
            --el-input-height: 48px;
            .el-input-group__append,
            .el-input-group__prepend {
                padding: 0px;
            }
        }
    }
}

.button {
    height: 40px;
}

.error-msg {
    line-height: 1;
}
</style>
